package org.developer.velocity.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.developer.velocity.app.service.MqMetadata;

import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class GenerateCodeByVelocityUtil {

    public static void generate(List<MqMetadata> metadata) {
        VelocityEngine ve = new VelocityEngine();

        //设置资源路径
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        //初始化
        ve.init();

        //载入模板
        Template t = ve.getTemplate("templates/mq.vm", StandardCharsets.UTF_8.name());

        //定义替换规则
        for (MqMetadata mqMetadata : metadata) {
            VelocityContext context = new VelocityContext();
            context.put("mqcode",mqMetadata.getMqCode());
            context.put("mqbodytype",mqMetadata.getMqBodyType());
            context.put("mqenumName",mqMetadata.getMqEnumName());

            if (mqMetadata.getComment() != null) {
                mqMetadata.setComment(mqMetadata.getComment().replaceAll("\"", ""));
                context.put("mqcomment",mqMetadata.getComment());
            }else{
                context.put("mqcomment","");

            }

            if (mqMetadata.getMqDesc() != null) {
                context.put("mqdesc", mqMetadata.getMqDesc().replaceAll("\"", ""));
            }else {
                context.put("mqdesc", "");

            }

            //存储合并后的结果
            StringWriter sw = new StringWriter();
            t.merge(context,sw);
            String r = sw.toString();

            System.out.println(r);
            System.out.println();
        }


    }
}
